package com.cafuc.base;

import com.cafuc.entity.User;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectOperation {

    public void reflectTest() throws Exception {
        User user = new User();
        Class clazz1 = User.class;
        Class clazz2 = Class.forName("com.cafuc.entity.User");
        Class clazz3 = user.getClass();
        System.out.println(clazz1 == clazz2);
        System.out.println(clazz3 == clazz2);
        System.out.println(clazz1.getName() + "-" +
                clazz1.getPackage().getName()+ "-" +
                clazz1.getSuperclass().getName() + "-" +
                clazz1.isInterface());

        User user1 = (User) clazz1.newInstance();
        System.out.println(user1.getUserName());
        Constructor<User> con1 = clazz1.getDeclaredConstructor(null);
        User user2 = con1.newInstance();
        System.out.println(user2.getUserName());
        Constructor<User> con2 = clazz1.getDeclaredConstructor(
                new Class[] {int.class, String.class, int.class});
        User user3 = con2.newInstance(new Object[] {1, "sun", 18});
        System.out.println(user3.getUserName());

        Field field = clazz1.getDeclaredField("name");
        field.setAccessible(true);
        field.set(user1, "smk");
        System.out.println(user1.getUserName());

        Method method = clazz1.getDeclaredMethod("call", null);
        method.setAccessible(true);
        method.invoke(user1, null);
    }

    public static void main(String[] args) throws Exception {
        ReflectOperation ro = new ReflectOperation();
        ro.reflectTest();

    }
}
